package com.stgy.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.stgy.lease.common.exception.StgyException;
import com.stgy.lease.common.result.ResultCodeEnum;
import com.stgy.lease.model.domain.PaymentType;
import com.stgy.lease.web.admin.service.PaymentTypeService;
import com.stgy.lease.web.admin.mapper.PaymentTypeMapper;
import org.springframework.stereotype.Service;

/**
 * @author lingx
 * @description 针对表【payment_type(支付方式表)】的数据库操作Service实现
 * @createDate 2024-08-28 11:00:29
 */
@Service
public class PaymentTypeServiceImpl extends ServiceImpl<PaymentTypeMapper, PaymentType>
        implements PaymentTypeService {

    @Override
    public boolean saveOrUpdatePaymentType(PaymentType paymentType) {
        if (paymentType == null || paymentType.getName() == null) {
            throw new StgyException(ResultCodeEnum.TERM_EXISTS_ERROR);
        }
        //获取传入的参数的id值，如果为空，返回一个数据库一定不存在的id值
//        Long id = paymentType.getId() == null ? -1 : paymentType.getId();
        Long id = paymentType.getId();
        LambdaQueryWrapper<PaymentType> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(PaymentType::getName, paymentType.getName());
        wrapper.last("limit 1");
        PaymentType one = this.getOne(wrapper);

        //新增：当one为空时，当id查询的记录为空 id=-1 one=null
        //更新：根据name查询数据库，one为空继续执行，不为空，并且id不相同 报错
        //one!=null && one.getId().equals(paymentType.getId())
        if (one != null && !one.getId().equals(paymentType.getId())) {
            //通过异常对象携带失败的code的值和message
//            throw new RuntimeException("支付方式名称已存在");
            throw new StgyException(ResultCodeEnum.PAYMENT_TYPE_EXISTS_ERROR);
        }
        return this.saveOrUpdate(paymentType);

        //name值唯一性校验
        //判断新增还是更新
//        Long id = paymentType.getId();
//        LambdaQueryWrapper<PaymentType> wrapper = new LambdaQueryWrapper<>();
//        wrapper.eq(PaymentType::getName, paymentType.getName());
//        wrapper.last("limit 1");
//        PaymentType one = this.getOne(wrapper);
//        if (id == null) {
//            //新增时，名称已存在
//            if (one != null) {
//                throw new RuntimeException("支付方式名称已存在");
//            }
//        } else {
//            //更新时，名称被占用，名称重复
//            if (one != null && !one.getId().equals(paymentType.getId())) {
//                throw new RuntimeException("支付方式名称已存在");
//            }
//        }
//        return this.saveOrUpdate(paymentType);
    }
}




